package com.xckj.cycling.fragment

import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ImageSpan
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.widget.doAfterTextChanged
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.junca.android.base.CViewBinding
import com.xckj.cycling.framework.MvvmUtils.lazyViewModel
import com.xckj.cycling.R
import com.xckj.cycling.activity.RouteLineDetailActivity
import com.xckj.cycling.databinding.FragmentRouteLineBinding
import com.xckj.cycling.databinding.ListIemSearchRouteBinding
import com.xckj.cycling.framework.BaseActivityKt
import com.xckj.cycling.framework.BaseFragmentKt
import com.xckj.cycling.model.RouteLineModel
import com.xckj.cycling.utils.FacebookShareUtils
import com.xckj.cycling.utils.StatusBarHelper
import com.xckj.cycling.utils.setColor
import com.xckj.cycling.utils.toFormattedTime
import com.xckj.cycling.viewmodel.RouteLineViewModel
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 线路
 */
class RouteLineFragment : BaseFragmentKt() {

    private val viewModel: RouteLineViewModel by lazyViewModel()

    @CViewBinding
    lateinit var viewBinding: FragmentRouteLineBinding
    private var keyword = ""
    private var type = ""
    private var page = 1
    private val adapter: RouteAdapter by lazy {
        RouteAdapter().apply {
            loadMoreModule.setOnLoadMoreListener {
                page++
                loadData()
            }
            setOnItemClickListener { adapter, view, position ->
                startActivity(
                    Intent(
                        requireContext(),
                        RouteLineDetailActivity::class.java
                    ).putExtra("id", data[position].id).putExtra("data", data[position])
                )
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        safeRegEventBus()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun event(model: RouteLineModel?) {
        model ?: return
        adapter.data.indexOfFirst { model.id == it.id }.let {
            if (it >= 0) {
                adapter.setData(it, model)
            }
        }
    }

    override fun initView(root: View, savedInstanceState: Bundle?) {
        super.initView(root, savedInstanceState)
        viewBinding.swipe.isRefreshing = true
        viewBinding.swipe.setColor()
        viewBinding.titlebar.btnBack.visibility = View.GONE
        viewBinding.swipe.setOnRefreshListener {
            page = 1
            loadData()
        }
        viewBinding.recyclerView.adapter = adapter
        viewBinding.titlebar.tvTitle.text = getString(R.string.route)
        viewBinding.filter.setOnClickListener {
            if (viewBinding.pop.root.visibility == View.GONE) {
                viewBinding.pop.root.visibility = View.VISIBLE
            } else {
                viewBinding.pop.root.visibility = View.GONE
            }
        }
        selectPop(0)
        viewBinding.pop.myPrivate.setOnClickListener {
            selectPop(2)
            viewBinding.pop.root.visibility = View.GONE
            type = "private"
            page = 1
            loadData()
        }
        viewBinding.pop.my.setOnClickListener {
            selectPop(3)
            viewBinding.pop.root.visibility = View.GONE
            type = "my"
            page = 1
            loadData()
        }
        viewBinding.pop.myHeart.setOnClickListener {
            selectPop(1)
            viewBinding.pop.root.visibility = View.GONE
            type = "collection"
            page = 1
            loadData()
        }
        viewBinding.pop.all.setOnClickListener {
            selectPop(0)
            viewBinding.pop.root.visibility = View.GONE
            type = ""
            page = 1
            loadData()
        }
        viewBinding.et.doAfterTextChanged {
            page = 1
            keyword = it.toString()
            loadData()
        }
        loadData()
    }

    private fun selectPop(index: Int) {
        when (index) {
            0 -> {
                text(viewBinding.pop.all, true)
                text(viewBinding.pop.myHeart, false)
                text(viewBinding.pop.myPrivate, false)
                text(viewBinding.pop.my, false)
            }

            1 -> {
                text(viewBinding.pop.all, false)
                text(viewBinding.pop.myHeart, true)
                text(viewBinding.pop.myPrivate, false)
                text(viewBinding.pop.my, false)
            }

            2 -> {
                text(viewBinding.pop.all, false)
                text(viewBinding.pop.myHeart, false)
                text(viewBinding.pop.myPrivate, true)
                text(viewBinding.pop.my, false)
            }

            3 -> {
                text(viewBinding.pop.all, false)
                text(viewBinding.pop.myHeart, false)
                text(viewBinding.pop.myPrivate, false)
                text(viewBinding.pop.my, true)
            }
        }
    }

    private fun text(textView: TextView, select: Boolean) {
        if (select) {
            val c = Color.parseColor("#0AD39F")
            textView.setTextColor(c)
            textView.compoundDrawableTintList = ColorStateList.valueOf(c)
        } else {
            val c = Color.WHITE
            textView.setTextColor(c)
            textView.compoundDrawableTintList = ColorStateList.valueOf(c)
        }
    }

    private fun loadData() {
        viewModel.loadRoute(page, keyword = keyword, type = type) {
            if (!it.isSuccessful) {
                showMessage(it.msg)
            }
            if (page == 1) {
                viewBinding.swipe.isRefreshing = false
                adapter.setNewInstance(it.data?.list ?: ArrayList())
            } else {
                it.data?.list?.apply {
                    adapter.addData(this)
                }
                adapter.loadMoreModule.loadMoreComplete()
            }
            if (adapter.data.isEmpty()) {
                viewBinding.emptyText.visibility = View.VISIBLE
            } else {
                viewBinding.emptyText.visibility = View.INVISIBLE
            }
            adapter.loadMoreModule.isEnableLoadMore = it.data?.list.isNullOrEmpty().not()
        }
    }

    override fun resumeAndNoHidden() {
        super.resumeAndNoHidden()
        StatusBarHelper.showStatusBar(requireActivity(), true)
    }

    inner class RouteAdapter :
        BaseQuickAdapter<RouteLineModel, RouteViewHolder>(R.layout.list_iem_search_route),
        LoadMoreModule {
        override fun convert(holder: RouteViewHolder, item: RouteLineModel) {
            holder.vb.routeInfo.distance.text = item.mileage.toString()
            holder.vb.routeInfo.totalKaluli.text = (item.calories ?: "0kcal")
            holder.vb.like.text = item.praisenum.toString()
            holder.vb.heart.text = item.collectionnum.toString()
            holder.vb.addr.text = item.endpost
            holder.vb.routeInfo.time.text = (item.actualDuration * 1000).toFormattedTime()
            holder.vb.routeInfo.totalAtt.text = item.climb ?: "0"
            holder.vb.collection.isSelected = item.iscollection
            holder.vb.praise.isSelected = item.ispraise
//            holder.vb.flag.visibility = if (item.isuser == 1) View.VISIBLE else View.GONE

            if (item.isuser == 1) {
                val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_flag)
                drawable?.setBounds(0, 0, 55, 62)
                val ss = SpannableString(item.name + " ")
                val span = drawable?.let { ImageSpan(it, ImageSpan.ALIGN_CENTER) }
                ss.setSpan(span, ss.length - 1, ss.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
                holder.vb.name.text = ss
            } else {
                holder.vb.name.text = item.name
            }

            Glide.with(holder.vb.root).load(item.fullimg).into(holder.vb.img)
            holder.vb.ground.text = item.ground_text
            holder.vb.share.setOnClickListener {
                FacebookShareUtils.shareImages(
                    requireActivity() as BaseActivityKt,
                    item.allShareImages.toTypedArray()
                )
//                FacebookShareUtils.shareFaceBookImage(requireActivity(), item.content, item.fullimg)
            }
            holder.vb.collection.setOnClickListener {
                showLoading()
                if (item.iscollection) {
                    viewModel.cancelCollect(item.id) {
                        hideLoading()
                        item.collectionnum = item.collectionnum - 1
                        item.iscollection = false
                        notifyDataSetChanged()
                    }
                } else {
                    viewModel.collect(item.id) {
                        hideLoading()
                        item.collectionnum = item.collectionnum + 1
                        item.iscollection = true
                        notifyDataSetChanged()
                    }
                }
            }
            holder.vb.praise.setOnClickListener {
                showLoading()
                if (item.ispraise) {
                    viewModel.cancelPraise(item.id) {
                        hideLoading()
                        item.praisenum = item.praisenum - 1
                        item.ispraise = false
                        notifyDataSetChanged()
                    }
                } else {
                    viewModel.praise(item.id) {
                        hideLoading()
                        item.praisenum = item.praisenum + 1
                        item.ispraise = true
                        notifyDataSetChanged()
                    }
                }
            }
        }


    }

    class RouteViewHolder(view: View) : BaseViewHolder(view) {
        val vb = ListIemSearchRouteBinding.bind(view)
    }
}